#include "stdlib.hpp"
#include <purewell/types.hpp>
#include <purewell/pairsocket.hpp>

namespace purewell
{

PWPairSocket::PWPairSocket() : m_op_idx(0)
{
}

PWPairSocket::~PWPairSocket()
{
}

void
PWPairSocket::setDefaultFile(size_t idx)
{
	m_op_idx = ( idx ? 1 : 0 );
}

size_t
PWPairSocket::getDefaultFile(void) const
{
	return m_op_idx;
}

bool
PWPairSocket::initialize(const char* name, int flags, int omode)
{
	int fd[2];
	if ( 0 != socketpair(AF_LOCAL, SOCK_STREAM, 0, fd) ) return false;

	if ( !attach2(fd) )
	{
		::close(fd[0]);
		::close(fd[1]);
		return false;
	}

	return true;
}

ssize_t
PWPairSocket::read(void* buf, size_t blen)
{
	return ::read( m_op_idx == 0 ? m_fd : m_fd2,
		(char*)buf, blen);
}

ssize_t
PWPairSocket::write(const void* buf, size_t blen)
{
	return ::write( m_op_idx == 0 ? m_fd : m_fd2,
		(const char*)buf, blen);
}

};//namespace purewell

